<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Markdown对话展示</title>
    <link href="https://cdn.staticfile.org/layui/2.9.6/css/layui.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github.min.css" rel="stylesheet">
    <style>
       .markdown-body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
            line-height: 1.8;
            color: #24292e;
            padding: 20px;
        }
        
        /* 层级缩进规则 */
        .markdown-body h1 { padding-left: 0; }
        .markdown-body h2 { padding-left: 1em; }
        .markdown-body h3 { padding-left: 2em; }
        .markdown-body h4 { padding-left: 3em; }
        .markdown-body h5 { padding-left: 4em; }
        .markdown-body h6 { padding-left: 5em; }
        
        /* 列表缩进 */
        .markdown-body ul,
        .markdown-body ol {
            padding-left: 2em;
        }
        
        /* 段落跟随标题缩进 */
        .markdown-body h1 + p,
        .markdown-body h1 + ul,
        .markdown-body h1 + ol { padding-left: 0; }
        
        .markdown-body h2 + p,
        .markdown-body h2 + ul,
        .markdown-body h2 + ol { padding-left: 1em; }
        
        .markdown-body h3 + p,
        .markdown-body h3 + ul,
        .markdown-body h3 + ol { padding-left: 2em; }
        
        /* 消息样式 */
        .message {
            margin-bottom: 20px;
            padding: 15px;
            border-radius: 5px;
            max-width: 85%;
        }
        .user-message {
            background-color: #e3f2fd;
            margin-left: auto;
            border: 1px solid #bbdefb;
        }
        .bot-message {
            background-color: #f5f5f5;
            margin-right: auto;
            border: 1px solid #e0e0e0;
        }
        
        /* 聊天容器 */
        #chatHistory {
            height: 500px;
            overflow-y: auto;
            padding: 15px;
            background-color: #fff;
        }
        
        /* 输入区域 */
        .input-area {
            margin-top: 20px;
            display: flex;
            gap: 10px;
        }
    </style>
</head>

<body>
    <div class="layui-container" style="margin-top: 20px;">
        <div class="layui-row">
            <div class="layui-col-md10 layui-col-md-offset1">
                <div class="layui-card">
                    <div class="layui-card-header">
                        <h2>智能对话助手</h2>
                    </div>
                    <div class="layui-card-body">
                        <div id="chatHistory" class="markdown-body"></div>
                        <div class="input-area">
                            <input type="text" id="userInput" class="layui-input" placeholder="请输入您的问题..." autocomplete="off">
                            <button class="layui-btn layui-btn-normal" id="sendBtn">发送</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.staticfile.org/layui/2.9.6/layui.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/markdown-it/13.0.2/markdown-it.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化Markdown解析器（使用默认配置，不修改原始内容）
            const md = window.markdownit({
                html: true,
                breaks: true,
                linkify: true,
                highlight: function(str, lang) {
                    if (lang && hljs.getLanguage(lang)) {
                        try {
                            return '<pre class="hljs"><code>' + 
                                   hljs.highlight(str, { language: lang }).value + 
                                   '</code></pre>';
                        } catch (__) {}
                    }
                    return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
                }
            });


            layui.use(['layer', 'jquery'], function() {
                const layer = layui.layer;
                const $ = layui.$;
                let currentContent = '';
                let conversationId = '';
                const chatHistory = document.getElementById('chatHistory');
                
                function addMessage(content, isUser) {
                    const messageDiv = document.createElement('div');
                    messageDiv.className = 'message ' + (isUser ? 'user-message' : 'bot-message');
                    
                    if (isUser) {
                        messageDiv.textContent = content;
                    } else {
                        // 仅做最小化处理：确保标题后有空格
                        const processedContent = content.replace(/^(#+)([^#\s])/mg, '$1 $2');
                        messageDiv.innerHTML = md.render(processedContent);
                        
                        // 动态应用缩进规则
                        setTimeout(() => {
                            const headings = messageDiv.querySelectorAll('h1,h2,h3,h4,h5,h6');
                            headings.forEach(heading => {
                                const level = parseInt(heading.tagName.substring(1));
                                heading.style.paddingLeft = `${level - 1}em`;
                                
                                // 处理跟随内容
                                let next = heading.nextElementSibling;
                                while(next && !next.matches('h1,h2,h3,h4,h5,h6')) {
                                    if (next.matches('p,ul,ol,pre')) {
                                        next.style.paddingLeft = `${level - 1}em`;
                                    }
                                    next = next.nextElementSibling;
                                }
                            });
                        }, 50);
                    }
                    
                    chatHistory.appendChild(messageDiv);
                    chatHistory.scrollTop = chatHistory.scrollHeight;
                }

                // 发送消息
                async function sendMessage() {
                    const userInput = document.getElementById('userInput');
                    const message = userInput.value.trim();
                    
                    if (!message) {
                        layer.msg('请输入问题');
                        return;
                    }
                    
                    addMessage(message, true);
                    userInput.value = '';
                    
                    const botResponseDiv = document.createElement('div');
                    botResponseDiv.className = 'message bot-message';
                    botResponseDiv.innerHTML = '<div class="typing-cursor"></div>';
                    chatHistory.appendChild(botResponseDiv);
                    
                    currentContent = '';
                    
                    try {
                        const response = await fetch('http://192.168.1.13/v1/chat-messages', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'Authorization': 'Bearer app-i0UAGSDgAgNc2kRMUKzaC70P'
                            },
                            body: JSON.stringify({
                                inputs: {},
                                query: message,
                                response_mode: "streaming",
                                user: "user-123",
                                conversation_id: conversationId
                            })
                        });

                        if (!response.ok) throw new Error(`请求失败: ${response.status}`);

                        const reader = response.body.getReader();
                        const decoder = new TextDecoder();
                        let buffer = '';

                        while (true) {
                            const { done, value } = await reader.read();
                            if (done) break;

                            buffer += decoder.decode(value, { stream: true });
                            const chunks = buffer.split('\n\n');
                            buffer = chunks.pop() || '';

                            for (const chunk of chunks) {
                                const cleanChunk = chunk.replace(/^data: /, '');
                                if (!cleanChunk) continue;

                                try {
                                    const eventData = JSON.parse(cleanChunk);
                                    if (eventData.event === 'message') {
                                        currentContent += eventData.answer;
                                        // 直接更新内容，不做格式处理
                                        botResponseDiv.innerHTML = md.render(currentContent) + 
                                                                 '<div class="typing-cursor"></div>';
                                        chatHistory.scrollTop = chatHistory.scrollHeight;
                                    }
                                } catch (error) {
                                    console.error('解析错误:', error);
                                }
                            }
                        }
                        
                        // 移除打字光标
                        botResponseDiv.querySelector('.typing-cursor')?.remove();
                        hljs.highlightAll();
                    } catch (error) {
                        console.error('Error:', error);
                        botResponseDiv.innerHTML = '<div class="layui-bg-red" style="padding: 10px;">请求出错: ' + 
                                                error.message + '</div>';
                    }
                }

                // 事件绑定
                document.getElementById('sendBtn').addEventListener('click', sendMessage);
                document.getElementById('userInput').addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') sendMessage();
                });
                
                // 初始欢迎消息
                addMessage('您好！我是智能助手，请直接输入您的问题，我将保持原始格式显示回答内容。', false);
            });
        });
    </script>
</body>
</html>